/**
 * @description 订单数据操作
 */

 const Order=require('../../models/Order')
 const Address=require('../../models/Address')
 const Product=require('../../models/Product')

 !(async()=>{
     //创建订单
     const requestBody={
         addressId:'60408a3b59a5a43bc0865351',
         shopId:'6040946438321f417029edc1',
         shopName:'沃尔玛',
         isCanceled:false,
         products:[
             {
                 id:'60409a0505e8cd4fd46df719',
                 num:3
             },{
                 id:'60409a0505e8cd4fd46df71a',
                 num:5
             }
         ]
     }
     //获取address
     const address=await Address.findById(requestBody.addressId)

     //获取商品列表
     const pIds=requestBody.products.map(p=>p.id) //['商品1id','商品2id']
     const productList=await Product.find({
         shopId:requestBody.shopId, //沃尔玛的商品
         _id:{
             $in:pIds
         }
     })
     
     //整合订单购买数量
     const productListWidthSales=productList.map(p=>{
         // 商品 id
         const id =p._id.toString()

         //找到商品的购买数量
         const filterProducts=requestBody.products.filter(item=>item.id===id)
         if (filterProducts.length===0) {
             throw Error('未找到匹配的销量数据')
         }
         return {
             product:p,
             orderSales:filterProducts[0].num
         }
     })
     
     await Order.create({
         username:'zhangsan',
         shopId:requestBody.shopId,
         shopName:requestBody.shopName,
         isCanceled:requestBody.isCanceled,
         address,
         products:productListWidthSales
     })
 })()